import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:cached_network_image/cached_network_image.dart';
import 'package:joyagoo/utils/route_utils.dart';
import '../../config/app_colors.dart';
import '../../config/app_url_address.dart';
import '../../model/productHotListModel.dart';
import '../../model/productListModel.dart';
import '../../utils/CountdownManager.dart';
import '../../utils/JoyCacheManager.dart';
import '../../utils/currency_manager.dart';
import '../joy_product_detail_page.dart';


class JoyProductCardWidget extends StatefulWidget {
  final ProductModel? productModel;
  final int? isCollection;
  final VoidCallback? onTap;
  final VoidCallback? onFavorite;

  const JoyProductCardWidget({
    super.key,
    this.isCollection = 0,
    this.productModel,
    this.onTap,
    this.onFavorite,
  });

  @override
  State<JoyProductCardWidget> createState() => _JoyProductCardWidgetState();
}

class _JoyProductCardWidgetState extends State<JoyProductCardWidget> {
  final CountdownManager _countdownManager = CountdownManager();
  CountdownData? _countdownData;
  bool _isActive = false;

  @override
  void initState() {
    super.initState();
    _initializeCountdown();
    _countdownManager.addListener(_onCountdownUpdate);
  }

  @override
  void dispose() {
    _countdownManager.removeListener(_onCountdownUpdate);
    super.dispose();
  }

  @override
  void didUpdateWidget(JoyProductCardWidget oldWidget) {
    super.didUpdateWidget(oldWidget);
    // 检查商品数据是否发生变化，包括所有关键字段
    if (oldWidget.productModel?.channelItemNo != widget.productModel?.channelItemNo ||
        oldWidget.productModel?.status != widget.productModel?.status ||
        oldWidget.productModel?.currentTime != widget.productModel?.currentTime ||
        oldWidget.productModel?.endTime != widget.productModel?.endTime) {
      _initializeCountdown();
    }
  }

  void _initializeCountdown() {
    final product = widget.productModel;
    if (product == null) return;

    // 检查是否有活动 (status == "1")
    _isActive = product.status == "1";
    
    // 调试信息
    String productId = product.id?.toString() ?? product.channelItemNo ?? "unknown";
    debugPrint('Product $productId: status=${product.status}, _isActive=$_isActive');
    debugPrint('Product $productId: currentTime=${product.currentTime}, endTime=${product.endTime}');
    debugPrint('Product $productId: discountRate=${product.discountRate}');

    if (_isActive && product.currentTime != null && product.endTime != null) {
      // 使用 channelItemNo 作为唯一键，因为 id 可能为 null
      String countdownKey = product.channelItemNo ?? "unknown_${DateTime.now().millisecondsSinceEpoch}";
      
      // 先添加倒计时数据到全局管理器
      _countdownManager.addCountdown(countdownKey, product.currentTime!, product.endTime!);
      
      // 然后获取倒计时数据
      _countdownData = _countdownManager.getCountdown(countdownKey);

      // 启动全局倒计时（如果还没启动）
      _countdownManager.startGlobalCountdown();
      
      debugPrint('Product $productId: 倒计时已启动，剩余时间=${_countdownData?.formattedTime}');
      debugPrint('Product $productId: countdownKey=$countdownKey, countdownData=${_countdownData?.isActive}');
    } else {
      _countdownData = null;
      debugPrint('Product $productId: 倒计时未启动，原因：_isActive=$_isActive, currentTime=${product.currentTime}, endTime=${product.endTime}');
    }
  }
  void _onCountdownUpdate() {
    if (mounted) {
      final product = widget.productModel;
      if (product != null) {
        String countdownKey = product.channelItemNo ?? "unknown_${DateTime.now().millisecondsSinceEpoch}";
        _countdownData = _countdownManager.getCountdown(countdownKey);
        setState(() {
          // 更新状态
        });
      }
    }
  }

  // 确保倒计时数据是最新的（解决 ListView 复用问题）
  void _ensureCountdownData() {
    final product = widget.productModel;
    if (product == null) return;

    // 如果当前没有倒计时数据，尝试重新获取
    if (_countdownData == null && _isActive && product.status == "1") {
      String countdownKey = product.channelItemNo ?? "unknown_${DateTime.now().millisecondsSinceEpoch}";
      _countdownData = _countdownManager.getCountdown(countdownKey);
      
      // 如果仍然没有数据，重新初始化
      if (_countdownData == null && product.currentTime != null && product.endTime != null) {
        _countdownManager.addCountdown(countdownKey, product.currentTime!, product.endTime!);
        _countdownData = _countdownManager.getCountdown(countdownKey);
        _countdownManager.startGlobalCountdown();
      }
    }
  }





  @override
  Widget build(BuildContext context) {
    // 在 build 方法中确保倒计时数据是最新的
    _ensureCountdownData();
    
    return GestureDetector(
      onTap:(){
        // 使用 Navigator.push 进行跳转
        Navigator.push(
          context,
          MaterialPageRoute(
            builder: (context) => JoyProductDetailPage(
              itemNo: (widget.isCollection == 0)? widget.productModel?.channelItemNo ?? "":widget.productModel?.spu ?? "",
              channel: widget.productModel?.channel ?? "",
              productName: widget.productModel?.title ?? "",
            ),
          ),
        );
      },
      child: Card(
        margin: EdgeInsets.zero,
        elevation: 8,
        shadowColor: Colors.black.withOpacity(0.15),
        color: Colors.white,
        shape: RoundedRectangleBorder(
          borderRadius: BorderRadius.circular(12.r),
        ),
        clipBehavior: Clip.antiAlias,
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            // 倒计时横幅
            if (_isActive && _countdownData != null && _countdownData!.isActive)
              _buildCountdownBanner(),
            // 商品图片
            Expanded(
              child: Stack(
                children: [
                  Column(
                    children: [
                      Expanded(
                        child: Container(
                          child: CachedNetworkImage(
                              cacheManager: JoyCacheManager.instance,
                              imageUrl:  showPictureUrl(widget.productModel?.mainImage??""),
                              width: double.infinity,
                              fit: BoxFit.cover,
                              placeholder: (context, url) => Container(
                                color: AppColors.backgroundSecondary,
                                child: Center(
                                  child: CircularProgressIndicator(
                                    strokeWidth: 2,
                                    valueColor: AlwaysStoppedAnimation<Color>(
                                      AppColors.textHint,
                                    ),
                                  ),
                                ),
                              ),
                              errorWidget: (context, url, error) => Container(
                                color: AppColors.backgroundSecondary,
                                child: Icon(
                                  Icons.image_not_supported,
                                  size: 32.sp,
                                  color: AppColors.textHint,
                                ),
                              ),
                            ),
                        ),
                      )
                    ],
                  ),
                  // 新品标签
                  if (isNewProduct())
                    Positioned(
                      bottom: 8.h,
                      left: 8.w,
                      child: Container(
                        padding: EdgeInsets.symmetric(
                          horizontal: 8.w,
                          vertical: 4.h,
                        ),
                        decoration: BoxDecoration(
                          gradient: LinearGradient(
                            colors: [
                              Color(0xFF00C9FF),
                              Color(0xFF92FE9D),
                            ],
                            begin: Alignment.topLeft,
                            end: Alignment.bottomRight,
                          ),
                          borderRadius: BorderRadius.circular(12.r),
                          boxShadow: [
                            BoxShadow(
                              color: Color(0xFF00C9FF).withOpacity(0.3),
                              blurRadius: 4,
                              offset: Offset(0, 2),
                            ),
                          ],
                        ),
                        child: Row(
                          mainAxisSize: MainAxisSize.min,
                          children: [
                            Icon(
                              Icons.fiber_new,
                              size: 12.sp,
                              color: Colors.white,
                            ),
                            SizedBox(width: 2.w),
                            Text(
                              'New',
                              style: TextStyle(
                                color: Colors.white,
                                fontSize: 10.sp,
                                fontWeight: FontWeight.bold,
                              ),
                            ),
                          ],
                        ),
                      ),
                    ),
                ],
              ),
            ),
            // 商品信息
            Padding(
              padding: EdgeInsets.all(12.w),
              child: Column(
                crossAxisAlignment: CrossAxisAlignment.start,
                children: [
                  Text(
                    widget.productModel?.title??"",
                    style: TextStyle(
                      fontSize: 14.sp,
                      fontWeight: FontWeight.w500,
                      color: AppColors.textHint,
                    ),
                    maxLines: 1,
                    overflow: TextOverflow.ellipsis,
                  ),
                  SizedBox(height: 4.h),
                  _buildPriceSection(),
                  SizedBox(height: 4.h),

                  showdiscountRate()

                ],
              ),
            ),
          ],
        ),
      ),
    );
  }
  // 构建价格显示区域
  Widget _buildPriceSection() {
    final product = widget.productModel;
    if (product == null) {
      return Text(
        "${CurrencyManager.instance.currentCurrency.symbol}0.00",
        style: TextStyle(
          fontSize: 16.sp,
          fontWeight: FontWeight.bold,
          color: AppColors.textPrimary,
        ),
      );
    }

    String displayPrice = "";
    String originalPrice = "";
    bool showDiscount = false;

    if (_isActive && product.status == "1" && _countdownData != null && _countdownData!.isActive) {
      // 活动期间：显示折扣价，原价作为对比
      displayPrice = product.price.toStringAsFixed(2);
      if (product.discountPrice != null && product.discountPrice! > 0) {
        originalPrice = product.discountPrice!.toStringAsFixed(2);
      }
      showDiscount = true;
    } else {
      // 非活动期间：优先显示原价，如果原价为null或0则显示折扣价
      if (product.discountPrice != null && product.discountPrice! > 0) {
        displayPrice = product.discountPrice!.toStringAsFixed(2);
        originalPrice = "";
      } else {
        displayPrice = product.price.toStringAsFixed(2);
        originalPrice = "";
      }
      showDiscount = false;
    }

    return Row(
      children: [
        Text(
          "${CurrencyManager.instance.currentCurrency.symbol}${displayPrice}",
          style: TextStyle(
            fontSize: 16.sp,
            fontWeight: FontWeight.bold,
            color: AppColors.textPrimary,
          ),
        ),
        if (originalPrice.isNotEmpty) ...[
          // SizedBox(width: 8.w),
          Text(
            "/${CurrencyManager.instance.currentCurrency.symbol}${originalPrice}",
            style: TextStyle(
              fontSize: 12.sp,
              color: AppColors.textHint,
              decoration: TextDecoration.lineThrough,
            ),
          ),
        ],
        // if (showDiscount && product.discountRate != null && product.discountRate! > 0) ...[
        //   SizedBox(width: 8.w),
        //   Container(
        //     padding: EdgeInsets.symmetric(horizontal: 6.w, vertical: 2.h),
        //     decoration: BoxDecoration(
        //       color: Color(0xFFFF6B35),
        //       borderRadius: BorderRadius.circular(4.r),
        //     ),
        //     child: Text(
        //       "${(product.discountRate! * 100).round()}% OFF",
        //       style: TextStyle(
        //         color: Colors.white,
        //         fontSize: 10.sp,
        //         fontWeight: FontWeight.bold,
        //       ),
        //     ),
        //   ),
        // ],
      ],
    );
  }

  Widget showdiscountRate(){
    final product = widget.productModel;
    if (product == null) return Container();

    double discountRates = product.discountRate ?? 0.0;

    // 根据活动状态判断是否显示折扣标签
    bool shouldShowDiscount = false;

    if (_isActive && product.status == "1" && _countdownData != null && _countdownData!.isActive) {
      // 活动期间：显示折扣标签
      shouldShowDiscount = discountRates > 0;
    } else {
      // 非活动期间：不显示折扣标签
      shouldShowDiscount = false;
    }

    // 调试信息
    String productId = product.id?.toString() ?? product.channelItemNo ?? "unknown";
    // debugPrint('Product $productId: 折扣标签判断 - shouldShowDiscount=$shouldShowDiscount, discountRates=$discountRates');
    // debugPrint('Product $productId: _isActive=$_isActive, status=${product.status}, countdownActive=${_countdownData?.isActive}');

    if (!shouldShowDiscount || discountRates == 0) {
      return Container();
    }

    return Container(
      padding: EdgeInsets.symmetric(horizontal: 4.w, vertical: 2.h),
      decoration: BoxDecoration(
        color: AppColors.backHomeYellowGround, // 浅橙色背景
        borderRadius: BorderRadius.circular(6.r),
        border: Border.all(
          color: AppColors.backHomeYellowGround, // 深橙色边框
          width: 1.0,
        ),
      ),
      child: Text(
        "${(discountRates * 100).round()}% OFF",
        style: TextStyle(
          color: AppColors.primaryVariant, // 深橙色文字
          fontSize: 12.sp,
          fontWeight: FontWeight.bold,
        ),
      ),
    );
  }

  // 构建倒计时横幅
  Widget _buildCountdownBanner() {
    return Container(
      width: double.infinity,
      margin: EdgeInsets.all(0.w),
      padding: EdgeInsets.symmetric(horizontal: 0.w, vertical: 4.h),
      decoration: BoxDecoration(
        color: AppColors.primaryVariant,
        borderRadius: BorderRadius.only(
            topLeft: Radius.circular(12.r),
            topRight: Radius.circular(12.r)
        ),
      ),
      child: Row(
        mainAxisAlignment: MainAxisAlignment.center,
        children: [
          Text(
            'Time Left: ',
            style: TextStyle(
              color: AppColors.garyVariant,
              fontSize: 12.sp,
              fontWeight: FontWeight.w500,
            ),
          ),
          Text(
            _countdownData?.formattedTime ?? '00H:00M:00S',
            style: TextStyle(
              color: AppColors.backHomeYellowGround,
              fontSize: 13.sp,
              fontWeight: FontWeight.bold,
            ),
          ),
        ],
      ),
    );
  }

  // 判断是否为新品（10天内创建的商品）
  bool isNewProduct() {
    // ProductModel 没有 createAt 字段，暂时返回 false
    // 如果需要新品判断，需要从后端获取创建时间数据
    return false;
  }

  String showPictureUrl(String url){

    String main = "";
    if(url.contains("http") || url.contains("https")){
      main =  url;
    }else{
      main = "${joyProductPicUrl}${url}";
    }

    String mainUrl = Uri.encodeFull(main);
    return mainUrl;
  }
}

// class JoyProductCardWidget extends StatelessWidget {
//   final ProductModel? productModel;
//   final VoidCallback? onTap;
//   final VoidCallback? onFavorite;
//
//   const JoyProductCardWidget({
//     super.key,
//     this.productModel,
//     this.onTap,
//     this.onFavorite,
//   });
//
//   @override
//   Widget build(BuildContext context) {
//     return GestureDetector(
//       onTap: (){
//         JoyNavUtils().to(JoyProductDetailPage(itemNo: productModel?.channelItemNo??"",channel: productModel?.channel??"",productName: productModel?.title??"",));
//
//       },
//       child: Container(
//         decoration: BoxDecoration(
//           color: Colors.white,
//           borderRadius: BorderRadius.circular(12.r),
//           boxShadow: [
//             BoxShadow(
//               color: Colors.black.withOpacity(0.05),
//               blurRadius: 8,
//               offset: const Offset(0, 2),
//             ),
//           ],
//         ),
//         child: Column(
//           crossAxisAlignment: CrossAxisAlignment.start,
//           children: [
//             // 商品图片
//             Expanded(
//               child: Stack(
//                 children: [
//                   Column(
//                     children: [
//                       Expanded(
//                         child: Container(
//                           child: ClipRRect(
//                             borderRadius: BorderRadius.vertical(
//                               top: Radius.circular(12.r),
//                             ),
//                             child: CachedNetworkImage(
//                               cacheManager: JoyCacheManager.instance,
//                               imageUrl:  showPictureUrl(productModel?.mainImageChannel??""),
//                               width: double.infinity,
//                               fit: BoxFit.cover,
//                               placeholder: (context, url) => Container(
//                                 color: AppColors.backgroundSecondary,
//                                 child: Center(
//                                   child: CircularProgressIndicator(
//                                     strokeWidth: 2,
//                                     valueColor: AlwaysStoppedAnimation<Color>(
//                                       AppColors.textHint,
//                                     ),
//                                   ),
//                                 ),
//                               ),
//                               errorWidget: (context, url, error) => Container(
//                                 color: AppColors.backgroundSecondary,
//                                 child: Icon(
//                                   Icons.image_not_supported,
//                                   size: 32.sp,
//                                   color: AppColors.textHint,
//                                 ),
//                               ),
//                             ),
//                           ),
//                         ),
//                       )
//                     ],
//                   ),
//                   // 新品标签
//                   if (isNewProduct())
//                     Positioned(
//                       bottom: 8.h,
//                       left: 8.w,
//                       child: Container(
//                         padding: EdgeInsets.symmetric(
//                           horizontal: 8.w,
//                           vertical: 4.h,
//                         ),
//                         decoration: BoxDecoration(
//                           gradient: LinearGradient(
//                             colors: [
//                               Color(0xFF00C9FF),
//                               Color(0xFF92FE9D),
//                             ],
//                             begin: Alignment.topLeft,
//                             end: Alignment.bottomRight,
//                           ),
//                           borderRadius: BorderRadius.circular(12.r),
//                           boxShadow: [
//                             BoxShadow(
//                               color: Color(0xFF00C9FF).withOpacity(0.3),
//                               blurRadius: 4,
//                               offset: Offset(0, 2),
//                             ),
//                           ],
//                         ),
//                         child: Row(
//                           mainAxisSize: MainAxisSize.min,
//                           children: [
//                             Icon(
//                               Icons.fiber_new,
//                               size: 12.sp,
//                               color: Colors.white,
//                             ),
//                             SizedBox(width: 2.w),
//                             Text(
//                               'NEW',
//                               style: TextStyle(
//                                 color: Colors.white,
//                                 fontSize: 10.sp,
//                                 fontWeight: FontWeight.bold,
//                               ),
//                             ),
//                           ],
//                         ),
//                       ),
//                     ),
//                 ],
//               ),
//             ),
//             // 商品信息
//             Padding(
//               padding: EdgeInsets.all(12.w),
//               child: Column(
//                 crossAxisAlignment: CrossAxisAlignment.start,
//                 children: [
//                   Text(
//                     this.productModel?.title??"",
//                     style: TextStyle(
//                       fontSize: 14.sp,
//                       fontWeight: FontWeight.w600,
//                       color: AppColors.textPrimary,
//                     ),
//                     maxLines: 1,
//                     overflow: TextOverflow.ellipsis,
//                   ),
//                   SizedBox(height: 4.h),
//                   Row(
//                     children: [
//                       Text(
//                         "\$${this.productModel?.price??0.00}",
//                         style: TextStyle(
//                           fontSize: 16.sp,
//                           fontWeight: FontWeight.bold,
//                           color: AppColors.textPrimary,
//                         ),
//                       ),
//                       // if (product['originalPrice'] != null)
//                       //   Text(
//                       //     product['originalPrice'],
//                       //     style: TextStyle(
//                       //       fontSize: 12.sp,
//                       //       color: AppColors.textHint,
//                       //       decoration: TextDecoration.lineThrough,
//                       //     ),
//                       //   ),
//                     ],
//                   ),
//                 ],
//               ),
//             ),
//           ],
//         ),
//       ),
//     );
//   }
//   // 判断是否为新品（10天内创建的商品）
//   bool isNewProduct() {
//     return false;
//   }
//
//   String showPictureUrl(String url){
//
//     String main = "";
//     if(url.contains("http")){
//       main =  url;
//     }else{
//       main = "${joyProductPicUrl}${url}";
//     }
//
//     String mainUrl = Uri.encodeFull(main);
//     return mainUrl;
//   }
//
// }